//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.only4play.authcenter.infrastructure.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.security.exception.CustomAuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

public class HandleHttpErrorUtil {
    private static final Logger log = LoggerFactory.getLogger(HandleHttpErrorUtil.class);
    private static final Integer AUTH_ERROR_CODE = 403;

    private HandleHttpErrorUtil() {
    }

    public static void handleHttpError(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws Exception {
        response.setStatus(200);
        response.setContentType("application/json");
        AuthResponse authResponse = new AuthResponse();
        if (CustomAuthenticationException.class.isAssignableFrom(e.getClass())) {
            CustomAuthenticationException cusException = (CustomAuthenticationException) e;
            authResponse.setCode(cusException.getCode());
            authResponse.setMsg(cusException.getMessage());
        } else {
            authResponse.setCode(AUTH_ERROR_CODE);
            authResponse.setMsg(e.getMessage());
        }

        ObjectMapper objectMapper = new ObjectMapper();
        response.getOutputStream().write(objectMapper.writeValueAsBytes(authResponse));
    }

    static class AuthResponse implements Serializable {
        private Integer code;
        private String msg;
        private Object result;

        public AuthResponse() {
        }

        public Integer getCode() {
            return this.code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getMsg() {
            return this.msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public Object getResult() {
            return this.result;
        }

        public void setResult(Object result) {
            this.result = result;
        }


    }
}
